<style scoped>
.clientCollection {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
.cc-top {
  padding: 15px 0;
  border-bottom: 2px solid #f4f4f4;
}
.cc-top div {
  display: flex;
}
.cc-top div p:first-child {
  margin: 3px 6px 0 0;
  white-space: nowrap;
  display: inline-block;
}
.cc-top div p:not(:first-child) {
  margin: 3px 6px 0 12px;
  white-space: nowrap;
  display: inline-block;
}
.cc-middle {
  padding: 1.5vh 0;
}

.wd {
  width: 8vw;
}
.cc-tab2 {
  margin: 1vh 0;
  font-weight: 700;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}

.clientCollection .summation {
  height: 4vh;
  background-color: #f5f7fa;
}
.clientCollection .summation p {
  line-height: 36px;
  float: right;
}
</style>

<style>
.clientCollection .el-input__inner {
  height: 30px;
}
.clientCollection .cc-top .el-date-editor .el-range__icon {
  line-height: 24px;
}
.clientCollection .cc-top .el-date-editor .el-range-separator {
  line-height: 24px;
  width: 8%;
}
.clientCollection .cc-top .el-input__icon {
  line-height: 30px;
}
.clientCollection .el-table__footer td {
  height: 36px;
}
</style>

<template>
  <div class="clientCollection">
    <!-- 客户收款结账 -->
    <div class="cc-top">
      <div>
        <p>客户</p>
        <!-- <el-input style="width:60px;margin-right:10px;" v-model="customerNo" @blur="customerNoBlur"></el-input> -->
        <el-select
          collapse-tags
          filterable
          clearable
          v-model="customerNo"
          style="width: 8vw"
          :disabled="jxAgent"
        >
          <el-option
            v-for="item in customerList"
            :key="item.value"
            :label="item.value + '  ' + item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <p>单号</p>
        <el-input class="wd" v-model="searchSequence"></el-input>
        <p>收款序号</p>
        <el-input
          class="wd"
          v-model="searchGatheringSequence"
          @keyup.enter.native="sequenceSearch"
        ></el-input>
        <p>折让金额</p>
        <el-input class="wd" v-model="discountMoney"></el-input>
        <p>收款金额</p>
        <el-input class="wd" v-model="gatheringMoney"></el-input>
        <p>日期</p>
        <el-date-picker
          unlink-panels
          style="width: 14vw"
          v-model="dateList"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <p>收款日期</p>
        <el-date-picker
          style="width: 150px"
          v-model="gatheringTime"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <!-- <el-input class="wd"></el-input> -->
      </div>
      <div style="margin-top: 10px">
        <p>订金</p>
        <el-input style="width: 8vw" v-model="earnest"></el-input>
        <p>缴付</p>
        <!-- <el-select v-model="pay" class="wd">
        <el-option v-for="item in payList" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select> -->
        <el-autocomplete
          clearable
          class="inline-input"
          v-model="pay"
          :fetch-suggestions="querySearchPay"
          style="width: 8vw"
        >
          <i class="el-input__icon" slot="suffix" key="venNew4"></i>
        </el-autocomplete>
        <p>收款序号</p>
        <el-input class="wd" disabled v-model="gatheringSequence"></el-input>
        <p>收支银行</p>
        <!-- <el-select v-model="incomeExpensesBanks" class="wd">
        <el-option v-for="item in bankList" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select> -->
        <el-autocomplete
          clearable
          class="inline-input"
          v-model="incomeExpensesBanks"
          :fetch-suggestions="querySearchBank"
          style="width: 8vw"
        >
          <i class="el-input__icon" slot="suffix" key="venNew4"></i>
        </el-autocomplete>
        <p>已收金额</p>
        <el-input class="wd" v-model="receivedOtherMoney"></el-input>
        <p>备注</p>
        <el-input style="width: 14vw" v-model="remark"></el-input>
      </div>
    </div>
    <div class="cc-middle">
      <el-button @click="search" type="primary" icon="el-icon-search"
        >查询</el-button
      >
      <el-button @click="settleAccounts" type="primary" icon="el-icon-bank-card"
        >结账</el-button
      >
      <el-button @click="modify" icon="el-icon-edit-outline">改单</el-button>
      <el-button v-print="'#outTable'" icon="el-icon-printer">列印</el-button>
      <el-button @click="dele" icon="el-icon-delete">删除</el-button>
    </div>
    <el-table
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      :data="tableData1"
      id="outTable"
      highlight-current-row
      show-summary
      ref="table"
      :summary-method="getSummaries"
      style="width: 100%"
      height="51vh"
      @row-click="rowClick"
    >
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <template v-for="i in ccList">
        <el-table-column
          :prop="i.prop"
          :key="i.prop"
          :label="i.label"
        ></el-table-column>
      </template>
    </el-table>
    <div class="summation">
      <p>
        销货数量：{{ sellNumber }} 退货数量：{{ outNumber }} 销货金额：{{
          sellMoney
        }}
        退货金额：{{ outMoney }} 其他应收：{{ otherReceivable }} 本期未收：{{
          thisUncollected
        }}
        本期应收：{{ thisReceivable }} 已收金额：{{ receivedMoney }}
      </p>
    </div>
    <div class="cc-tab2">
      <p>收款单据</p>
    </div>
    <el-table
      highlight-current-row
      :data="tableData2"
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      style="width: 100%"
    >
      <el-table-column
        prop="gatheringSequence"
        label="收款序号"
        width="160"
      ></el-table-column>
      <el-table-column prop="customerNo" label="客户编号"></el-table-column>
      <el-table-column prop="discountMoney" label="折让金额"></el-table-column>
      <el-table-column prop="earnest" label="订金"></el-table-column>
      <el-table-column prop="gatheringMoney" label="收款金额"></el-table-column>
      <el-table-column
        prop="receivedOtherMoney"
        label="已收其他金额"
      ></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="getTime" label="收款日期"></el-table-column>
      <el-table-column prop="curency" label="币种"></el-table-column>
      <el-table-column
        prop="operator"
        label="操作员"
        width="120"
      ></el-table-column>
    </el-table>
    <foot-view class="footView">
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
    <!-- 改单 -->
    <modify-document
      v-show="showModify"
      :payList="payList"
      :bankList="bankList"
      :detailList="tableData2"
      :customerMap="customerMap"
      @closeMD="
        () => {
          this.showModify = false
        }
      "
    ></modify-document>
  </div>
</template>

<script>
import { getClient } from '../../../network/client'
import {
  list,
  add,
  del,
  bankList,
  insert,
  getObjBySequence
} from '../../../network/customerGathering'

import footView from '../../../components/FootView'
import ModifyDocument from './childComps/ModifyDocument'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'

export default {
  name: 'client_collection',
  mixins: [today, enterUp],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let jxAgentVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null
   if(jxAgentVal){
    this.jxAgent = jxAgentVal[1] == 1 ? true : false
   }
    
    this.inpList = this.getInput()
    // 获取所有客户信息
    getClient({ limit: 99999 }).then((res) => {
      // // console.log(res)
      if (res.data.code == 200) {
        let list = res.data.data
        this.customerList = []
        this.customerMap = {}
        list.forEach((e) => {
          if (e.stop != 1) {
            this.customerList.push({ value: e.no, label: e.name })
          }
          this.customerMap[e.no] = e.name
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customerNo = i.value
              break
            }
          }
        }
      }
    })

    bankList().then((res) => {
      // // console.log(res)
      res.data.data.forEach((e) => {
        this.payList.push({ value: e.pay, label: e.pay })
        this.bankList.push({ value: e.bank, label: e.bank })
      })
    })
  },
  components: {
    footView,
    ModifyDocument
  },
  data() {
    return {
      inpList: [],
      showModify: false,

      customerNo: '',
      customerList: [],
      customerMap: {},
      sequence: '',
      searchSequence: '',
      searchGatheringSequence: '',
      discountMoney: '',
      gatheringMoney: '',
      dateList: null,
      gatheringTime: this.searchDate(0),
      earnest: '',
      pay: '',
      payList: [],
      gatheringSequence: '',
      incomeExpensesBanks: '',
      bankList: [],
      receivedOtherMoney: '',
      remark: '',
      tableData1: [],
      tableData2: [],
      ccList: [
        { prop: 'sequence', label: '单号', width: '160' },
        { prop: 'customerNo', label: '客户编号', width: '' },
        { prop: 'sellNumber', label: '销货数量', width: '' },
        { prop: 'sellOutNumber', label: '退货数量', width: '' },
        { prop: 'sellMoney', label: '销货金额', width: '' },
        { prop: 'sellOutMoney', label: '退货金额', width: '' },
        { prop: 'otherIncome', label: '其他应收', width: '' },
        { prop: 'dateTime', label: '日期', width: '' }
      ],

      outMoney: 0,
      outNumber: 0,
      receivedMoney: 0,
      sellMoney: 0,
      sellNumber: 0,
      thisReceivable: 0,
      thisUncollected: 0,
      otherReceivable: 0,
      jxQuarter: null,
      jxAgent:null,
      operator:null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1],
      // jxAgent:
      //   document.cookie.match(RegExp('jxAgent' + '=([^;]+)'))[1] == 1
      //     ? true
      //     : false,
      // operator: document.cookie.match(RegExp('jxUser' + '=([^;]+)'))[1]
    }
  },
  methods: {
    querySearchPay(queryString, cb) {
      cb(this.payList)
    },
    querySearchBank(queryString, cb) {
      cb(this.bankList)
    },
    // 折让金额  收款金额获得焦点时候查
    search() {
      let params = {
        customerNo: String(this.customerNo),
        sequence: this.searchSequence,
        startTime: this.dateList ? this.dateList[0] + ' 00:00:00' : '',
        endTime: this.dateList ? this.dateList[1] + ' 23:59:59' : ''
      }
      list(params).then((res) => {
        // // console.log(res)
        if (res.data.code == 200) {
          this.tableData1 =
            res.data.data.customerConsignmentReconciliationOneVOList

          let tmp = res.data.data.customerGatheringTwoVO
          this.outMoney = tmp.outMoney
          this.outNumber = tmp.outNumber
          this.receivedMoney = tmp.receivedMoney
          this.sellMoney = tmp.sellMoney
          this.sellNumber = tmp.sellNumber
          this.thisReceivable = tmp.thisReceivable
          this.thisUncollected = tmp.thisUncollected

          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })

          this.tableData1.forEach((e) => {
            for (const key in e) {
              if (Object.hasOwnProperty.call(e, key)) {
                const element = e[key]
                if (!element) e[key] = ''
              }
            }
          })
        }
      })
    },
    // 结账
    settleAccounts() {
      if (!this.customerNo.length) {
        this.$alert('客户不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      // if (!String(this.discountMoney)) {
      //   this.$alert('折让金额不能为空', '', {
      //     confirmButtonText: '确定'
      //   })
      //   return
      // }
      if (!String(this.gatheringMoney)) {
        this.$alert('收款金额不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!String(this.gatheringTime)) {
        this.$alert('收款日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      // if (!String(this.earnest)) {
      //   this.$alert('订金不能为空', '', {
      //     confirmButtonText: '确定'
      //   })
      //   return
      // }
      let d = {
        customerNo: String(this.customerNo),
        discountMoney: this.discountMoney || 0,
        gatheringMoney: this.gatheringMoney,
        gatheringTime: this.gatheringTime,
        // gatheringTime: '2020-08-08',
        earnest: this.earnest || 0,
        pay: this.pay,
        incomeExpensesBanks: this.incomeExpensesBanks,
        receivedOtherMoney: this.receivedOtherMoney,
        remark: this.remark,
        curency: '￥'
      }
      add(JSON.stringify(d)).then((res) => {
        // console.log(res)
        if (res.data.code == 200) {
          res.data.data.getTime =
            res.data.data && res.data.data.gatheringTime.slice(0, 10)
          this.tableData2 = [res.data.data]

          this.$message.success('录入成功')

          if (this.pay || this.incomeExpensesBanks) {
            insert(
              JSON.stringify({
                pay: this.pay,
                bank: this.incomeExpensesBanks
              })
            ).then((res) => {
              // console.log(res)
            })
          }
        }
      })
    },
    sequenceSearch() {
      this.tableData2 = []
      getObjBySequence({ sequence: this.searchGatheringSequence }).then(
        (res) => {
          // console.log(res)
          if (res.data.code == 200) {
            if (res.data.data) {
              res.data.data.getTime = res.data.data.gatheringTime.slice(0, 10)
              this.tableData2 = [res.data.data]
            }
          }
        }
      )
    },
    dele() {
      if (!this.sequence) {
        this.$message.info('请先选择一条数据再进行删除')
        return
      }
      if (this.sequence.slice(0, 1) == 'K') {
        this.$message.warning('此功能无法删除客销数据')
        return
      } else if (this.sequence.slice(0, 1) == 'Q') {
        this.$message.warning('此功能无法删除其他应收数据')
        return
      } else {
        del({ sequence: this.sequence }).then((res) => {
          // console.log(res)
          if (res.data.code == 200) {
            this.$message.success('删除成功')
            this.sequence = ''
            this.tableData2 = []
            this.search()
          } else {
            this.$message.error('删除失败')
          }
        })
      }
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map((item) => Number(item[prop]))
        if (!values.every((value) => isNaN(value))) {
          if (
            prop == 'sellNumber' ||
            prop == 'outNumber' ||
            prop == 'sellMoney' ||
            prop == 'outMoney' ||
            prop == 'otherIncome'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (!sums[index]) {
              sums[index] = ''
            }
            let decimal = sums[index].toString().split('.')[1]
            if (decimal && decimal.length > 2) {
              sums[index] = sums[index].toFixed(2)
            }
          }
        }
      })
      return sums
    },

    rowClick(row) {
      this.tableData2 = []
      this.sequence = row.sequence
      if (this.sequence[0] == 'C') {
        getObjBySequence({ sequence: this.sequence }).then((res) => {
          // console.log(res)
          res.data.data.getTime = res.data.data.gatheringTime.slice(0, 10)
          this.tableData2 = [res.data.data]
        })
      }
    },

    modify() {
      if (this.sequence[0] == 'C') {
        this.showModify = true
      } else {
        this.$message.info('此单不可改')
      }
    }
  }
}
</script>
